let logger = require("pomelo-logger").getLogger(__filename);
let amqp = require('amqplib/callback_api');

let AmqpService = function (app) {
    this.app = app;
};

AmqpService.prototype.sendMsg = function (exchange, routeKey, msg) {
    let amqpConfig = this.app.get('amqpConfig');
    amqp.connect(amqpConfig, function(error, connection) {
        if(!!error) {
            logger.error(' Caught exception error---------: ' + error);
            return;
        }
        connection.createChannel(function(error, channel) {
            if(!!error) {
                logger.error(' Caught exception error---------: ' + error);
                return;
            }
            channel.assertExchange(exchange, 'direct', {durable: true});
            channel.publish(exchange, routeKey, new Buffer(JSON.stringify(msg)));
            logger.info(" [x] Sent %s", JSON.stringify(msg));

        });
        setTimeout(function() { connection.close() }, 3000);
    });
};

module.exports.create = function (app) {
    return new AmqpService(app);
};